package tests

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"interview/models"
	"interview/pkg/global"
)

// Mysql 初始化MySQL
func Mysql() {
	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%d)/%s?%s",
		global.Conf.Mysql.Username,
		global.Conf.Mysql.Password,
		global.Conf.Mysql.Host,
		global.Conf.Mysql.Port,
		global.Conf.Mysql.Database,
		global.Conf.Mysql.Query,
	)
	gormConfig := gorm.Config{}
	if global.Conf.Mysql.LogMode {
		gormConfig.Logger = logger.Default.LogMode(logger.Info)
	}

	db, err := gorm.Open(mysql.Open(dsn), &gormConfig)
	if err != nil {
		global.Logger.Panicf("[单元测试]初始化MySQL异常：%v", err)
	}
	global.Db = db
	autoMigrate()
	global.Logger.Debug("[单元测试] 初始化MySQL完毕")
}

// 自动迁移表结构
func autoMigrate() {
	global.Db.AutoMigrate(
		new(models.User),
		new(models.SysRole),
		new(models.SysMenu),
		new(models.SysApi),
		new(models.SysCasbin),
		new(models.SysWorkflow),
		new(models.SysWorkflowNode),
		new(models.SysWorkflowLine),
		new(models.SysWorkflowLog),
		new(models.RelationUserWorkflowNode),
		new(models.RelationWorkflowLineNode),
	)
}
